package o2o.web.actions.area;

import com.jinyou.utils.common.AjaxResult;
import net.sf.json.JSONObject;
import o2o.area.ChnAreaMemory;
import o2o.cache.area.CityMemory;
import o2o.cache.area.CountyMemory;
import o2o.cache.area.ProvinceMemory;
import o2o.config.dao.DataDaoSql;
import o2o.dao.PO.common.ResultInfo;
import o2o.service.area.AreaExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qilonghe【1061268464@qq.com】
 * @ClassName AreaExcelController
 * @Description:
 * @date 2020/10/20 0020 下午 6:12
 * @Version 1.0
 */
@RestController
public class AreaExcelController {
    @Autowired
    AreaExcelService areaExcelService;

    // Excel导入省市区信息
    @RequestMapping(method = RequestMethod.POST, value = "admin/area/excelImport")
    public String excelImport(MultipartFile file) {
        if (file == null) {
            return AjaxResult.errorResult("导入Excel文件不能为空");
        }

        Connection con = null;
        try {
            con = DataDaoSql.getInstance().getConnection();
            con.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
            DataDaoSql.getInstance().close(con);
            return AjaxResult.errorResult("数据库获取连接异常，请稍后再试");
        }

        try {
            ResultInfo resultInfo = areaExcelService.excelImport(file, con);

            if (resultInfo.isSuccess()) {
                con.commit();

                // 刷新缓存
                ProvinceMemory.getInstance().run();
                CityMemory.getInstance().run();
                CountyMemory.getInstance().run();
                ChnAreaMemory.getInstance().run();

                return AjaxResult.successResult();
            }

            DataDaoSql.getInstance().rollback(con);

            Map<String, String> map = new HashMap<>();
            map.put("error", resultInfo.getError());
            StringBuffer buffer = new StringBuffer();
            buffer.append("{\"status\":0,")
                    .append("\"type\":\"comError\",\"error\":")
                    .append(JSONObject.fromObject(map))
                    .append("}");
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            DataDaoSql.getInstance().rollback(con);
            return AjaxResult.errorResult("导入异常，请稍后再试");
        } finally {
            DataDaoSql.getInstance().close(con);
        }
    }
}